package fa7.socialcode.web;

import java.text.MessageFormat;
import java.util.ResourceBundle;

import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import fa7.socialcode.model.Categoria;
import fa7.socialcode.model.Usuario;
import fa7.socialcode.service.CategoriaManager;

public class CategoriaForm {
	private final Log log = LogFactory.getLog(CategoriaForm.class);
	private String id;
	public Categoria categoria = new Categoria();
	public CategoriaManager mgr;
	private Usuario usuarioInSession;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Categoria getCategoria() {
		return categoria;
	}

	public void setCategoria(Categoria categoria) {
		this.categoria = categoria;
	}

	public void setCategoriaManager(CategoriaManager categoriaManager) {
		this.mgr = categoriaManager;
	}
	
	public Usuario getUsuarioInSession() {
		return usuarioInSession;
	}

	public void setUsuarioInSession(Usuario usuarioInSession) {
		this.usuarioInSession = usuarioInSession;
	}

	public String edit() {

		if (id != null) {
			// assuming edit
			setCategoria(mgr.findCategoria(id));
		}

		return "success";
	}

	public String save() {
		Categoria ex = getCategoria();
		if (ex.getId() == 0) {
			ex.setId(null);
		}
		mgr.saveCategoria(ex);
		addMessage("categoria.saved", getCategoria().getCategoria());

		return "success";
	}

	public String delete() {
		mgr.removeCategoria(getCategoria().getId().toString());
		addMessage("categoria.deleted", getCategoria().getDescricao());

		return "success";
	}

	// Convenience methods ====================================================
	public static String getRequestParameter(String name) {
		return (String) FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap().get(name);
	}

	public void addMessage(String key, String arg) {
		// sure is a lot of work to get the named ResourceBundle in JSF, eh?
		ApplicationFactory factory = (ApplicationFactory) FactoryFinder
				.getFactory(FactoryFinder.APPLICATION_FACTORY);
		String bundleName = factory.getApplication().getMessageBundle();
		ResourceBundle messages = ResourceBundle.getBundle(bundleName);

		// it's even more work to format a message with args
		MessageFormat form = new MessageFormat(messages.getString(key));

		String msg = form.format(new Object[] { arg });

		// add message to session so it can live past redirects
		// the MessageFilter class will take care of removing it
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		session.setAttribute("message", msg);
	}
}
